package com.snopy.mq.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author snopy
 * @version 1.0.0
 * @classname Worker
 * @description
 * @email 77912204@qq.com
 * @date 2022/05/29 18:34
 */
public class Worker2 {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.101.45.196");
        factory.setPort(5672);
        try(Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);

            while (true){
                DeliverCallback deliverCallback = (consumerTag, delivery)->{

                    String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
                    System.out.println("[x] Received :"+msg);
                    try {
                        doWork(msg);
                        Thread.yield();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        System.out.println("[x] Done");
                    }
                };

                channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag->{});
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
    private static void doWork(String task) throws InterruptedException {
        for (char ch:task.toCharArray()){
            if (ch == '.'){
                System.out.println("[x] work hard..");
                Thread.sleep(1000);
            }
        }
    }
}
